package com.yhcnet.controller;

import com.yhcnet.po.Login;
import com.yhcnet.po.Result;
import com.yhcnet.po.UuidAndAva;
import com.yhcnet.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Result login(@RequestBody Login login) {
        if(login == null) {
            return Result.fail("账号或密码错误！");
        }

        // 先检测验证码是否正确
        if(!userService.codeCheck(login)){
            return Result.fail("验证码错误！");
        }

        // 再判断账号和密码是否正确
        String uuid = userService.login(login);

        if(uuid == null) {
            return Result.fail("账号或密码错误！");
        }

        UuidAndAva uuidAndAva = new UuidAndAva();
        uuidAndAva.setUuid(uuid);
        uuidAndAva.setAvatar(userService.getAva(uuid));

        return Result.succ(uuidAndAva);
    }

    /**
     * 不开放注册，待完善
     * @return
     */
    @PostMapping("/regist")
    public Result regist(@RequestBody Login regist) {
        if(regist == null) {
            return Result.fail("注册失败，请重试！");
        }

        // 先检测验证码是否正确
        if(!userService.codeCheck(regist)){
            return Result.fail("验证码错误！");
        }

        if(userService.checkUserAlready(regist.getUsername())){
            return Result.fail("用户名重复，请重试！");
        }

        if(userService.regist(regist)){
            return Result.succ(null);
        }

        return Result.fail("注册失败，请重试！");
    }

}